package com.pl.config.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.pl.bean.ResultData;
import com.pl.util.ResultDataUtil;

/**
 * class name:MyAuthenctiationFailureHandler <BR>
 * class description: 认证失败的自定义处理 <BR>
 * Remark: <BR>
 * @version 1.00 2019年11月22日
 * @author wangjian
 */
@Component
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	
	private static Logger log = LogManager.getLogger();
 
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    	
    	log.debug("request.getSession().getId() = {},  exception={}", request.getSession().getId(), exception.getMessage());
    	if(request.getSession().getAttributeNames().hasMoreElements()) {
    		String key = request.getSession().getAttributeNames().nextElement();
    		log.debug("key={},  value={}", key, request.getSession().getAttribute(key));
    	}
    	
    	/*
    	 * UsernameNotFoundException（用户不存在）
    	 * DisabledException（用户已被禁用）
    	 * BadCredentialsException（坏的凭据）
    	 * LockedException（账户锁定）
    	 * AccountExpiredException （账户过期）
    	 * CredentialsExpiredException（证书过期）
    	 */
    	
    	ResultData<String> result = ResultDataUtil.fail(exception.getMessage());
		/*
		 * if(exception instanceof BadCredentialsException) { result =
		 * ResultDataUtil.fail("用户名或者密码错误"); }
		 */
    	
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        
        PrintWriter out = response.getWriter();
        
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
}
